<!-- src/views/CreateAnnouncementView.vue -->
<template>
  <div class="create-announcement-container" v-loading="loading">
    <el-page-header @back="$router.go(-1)" content="发布公告" style="margin-bottom: 20px;" />

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <!-- 创建公告表单 -->
    <el-card class="create-announcement-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>填写公告信息</span>
        </div>
      </template>
      <el-form
        ref="announcementFormRef"
        :model="announcementForm"
        :rules="announcementRules"
        label-width="100px"
        @submit.prevent="submitAnnouncement"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="announcementForm.title"
            placeholder="请输入公告标题"
            maxlength="255"
            show-word-limit
            size="large"
          />
        </el-form-item>

        <el-form-item label="公告类型" prop="type">
          <el-radio-group v-model="announcementForm.type">
            <el-radio :label="1">普通公告</el-radio>
            <el-radio :label="2">重要公告</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="公告内容" prop="content">
          <!-- 可以根据需要替换为富文本编辑器，如 WangEditor, Quill.js -->
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="15"
            placeholder="请输入公告内容..."
            maxlength="65535"
            show-word-limit
            size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAnnouncement" :loading="saving" size="large">
            发布公告
          </el-button>
          <el-button @click="resetForm" size="large">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成功提示 -->
    <div v-if="successMessage" class="success-message">
      {{ successMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { createAnnouncement } from '@/services/apiService'; // 引入创建公告的 API 服务
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

const announcementFormRef = ref();
const loading = ref(false);
const saving = ref(false);
const errorMessage = ref('');
const successMessage = ref('');

const announcementForm = reactive({
  title: '',
  content: '',
  type: 1 // 默认普通公告
});

const announcementRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 1, max: 255, message: '标题长度为 1 到 255 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' } // 注意是 change
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 1, max: 65535, message: '内容长度不能超过 65535 个字符', trigger: 'blur' }
  ]
};

// 提交公告
const submitAnnouncement = async () => {
  if (!announcementFormRef.value) return;
  await announcementFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      errorMessage.value = '';
      successMessage.value = '';
      try {
        // --- 调用真实的后端 API ---
        const response = await createAnnouncement({
          title: announcementForm.title,
          content: announcementForm.content,
          type: announcementForm.type
        });
        console.log('Announcement created:', response.data);
        ElMessage.success('公告发布成功！');
        successMessage.value = '公告发布成功！';
        // 发布成功后，跳转到公告列表页或首页
        // router.push('/announcements'); // 如果有公告列表页
        router.push('/'); // 跳转到首页
      } catch (error) {
        console.error('Announcement creation failed:', error);
        errorMessage.value = error.response?.data?.message || '发布公告失败';
        ElMessage.error(errorMessage.value);
      } finally {
        saving.value = false;
      }
    } else {
      console.log('Announcement form validation failed!');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  announcementForm.title = '';
  announcementForm.content = '';
  announcementForm.type = 1;
  if (announcementFormRef.value) {
    announcementFormRef.value.resetFields();
  }
  successMessage.value = '';
  errorMessage.value = '';
};

// 组件挂载时检查权限
onMounted(() => {
  // 检查用户是否已认证并且用户名是 'lgt'
  if (!authStore.isAuthenticated || authStore.currentUser?.username !== 'lgt') {
    ElMessage.error('权限不足：仅限用户名为 lgt 的用户可以发布公告。');
    router.push('/'); // 或者跳转到 403 页面
  }
});
</script>

<style scoped>
.create-announcement-container {
  padding: 20px;
  max-width: 1000px; /* 限制最大宽度 */
  margin: 0 auto;
}

.create-announcement-card {
  /* 可以添加卡片样式 */
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: bold;
  font-size: 1.2em;
  color: #333;
}

.success-message {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  color: #67c23a;
  text-align: center;
  font-size: 1em;
}
</style>
